import ast
import os
import subprocess

from utils import sr_s3
import agent_config


def add_watermark_via_service(input_video_path, output_video_path, task_id, watermark_size="720p", extract_thumbnail=False, extract_watermark=False, nsfw_check=False):
    """
    调用外部水印服务添加水印到视频

    Args:
        input_video_path (str): 输入视频路径
        task_id (str): 任务ID
        watermark_size (str): 水印尺寸
        extract_thumbnail (bool): 是否提取缩略图
        extract_watermark (bool): 是否提取缩略图
        nsfw_check (bool): 是否进行NSFW检测

    Returns:
        dict: 包含处理结果的字典
        python add_watermark_service.py test_001_video.mp4 --output-video output.mp4 --taskid my_task_123 --watermark-size 720p
    """

    input_video = os.path.abspath(input_video_path)
    output_video = os.path.abspath(output_video_path)

    if extract_watermark is False:
        watermark_size = 0  # 0表示不添加水印

    # try:
    # 构建命令
    cmd = [
        "python", "add_watermark_service.py",
        input_video,
        "--output-video", output_video,
        "--taskid", str(task_id),
        "--watermark-size", str(watermark_size)
    ]

    # 动态添加可选参数
    if extract_thumbnail:
        cmd.append("--extract-thumbnail")
    if nsfw_check:
        cmd.append("--nsfw-check")

    # 执行命令
    print(f"👉 执行命令: {' '.join(cmd)}")
    sr_s3.set_logging(f"执行命令{task_id}: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=10000)

    if result.returncode == 0:
        # 命令执行成功，尝试解析输出
        return {
            "status": 1,
            "code": "",
            "msg": "",
            "err_json": {}
        }
    else:
        # 解析输出中的错误码
        error_code = result.returncode  # 默认使用返回码

        # 建立映射关系：实际退出码 -> 50开头的错误码
        exit_code_mapping = {
            11: 5011,  # 输入文件或水印文件不存在
            12: 5012,  # 提取缩略图失败
            13: 5013,  # 添加水印失败
            14: 5014,  # 提取帧失败
            15: 7201  # NSFW检测不通过
        }
        # 如果在映射中找到对应关系，则使用映射的错误码
        if error_code in exit_code_mapping:
            error_code = exit_code_mapping[error_code]
        else:
            print("水印没有预期的错误码，请检查水印服务代码")

        # 根据不同的退出码返回不同的错误信息
        error_messages = {
            5011: "输入文件或水印文件不存在",
            5012: "提取缩略图失败",
            5013: "添加水印失败",
            5014: "提取帧失败",
            7201: "NSFW触发风控",
        }
        error_msg = error_messages.get(error_code, "未知错误")
        threshold = {}
        if error_code == 7201:
            # 目标标记（外部命令中需要输出的内容要包含这个标记）
            target_mark = "[ERR_MESSAGE]"
            # 分割子进程的所有输出（按行处理）
            all_output_lines = result.stdout.splitlines()
            # 筛选包含目标标记的行
            target_lines = [line for line in all_output_lines if target_mark in line]
            status = 1  # 判断是否放行
            # 如果有多个目标行，这里取第一行（可根据需求调整）
            if target_lines:
                #  去除标记，只保留核心内容
                threshold = target_lines[0].replace(target_mark, "").strip()
                print('threshold', threshold)

            return {
                "status": 1,
                "code": error_code,
                "msg": f"{error_msg}",
                "err_json": threshold,
            }
        else:  # 其他错误都放行,记录错误
            return {
                "status": 1,
                "code": error_code,
                "msg": f"水印服务执行失败: {error_msg}",
                "err_json": threshold,
            }

    # except subprocess.TimeoutExpired:
    #     return {
    #         "status": 1,
    #         "code": 5010,
    #         "msg": "执行超时",
    #         "err_json": {}
    #     }
    # except Exception as e:
    #     return {
    #         "status": 1,
    #         "code": 5010,
    #         "msg": f"服务异常: {str(e)}",
    #         "err_json": {}
    #     }


def process_video_with_watermark_service(local_video_path, task_id, resolution, storage_service="", bucket_name="", s3_prefixes_path="video/resources/", extract_thumbnail=False, extract_watermark=False, nsfw_check=False):
    """
    处理视频水印的完整流程
    """
    # try:
    # 2. 调用水印服务
    # 生成输出视频路径

    output_video_path = "./download/" + task_id + f"/_watermarked.mp4"
    thumbnail_path = "./download/" + task_id + f"/_thumbnail.png"
    print("生成输出视频路径", local_video_path, output_video_path, task_id, resolution, storage_service, bucket_name, s3_prefixes_path, extract_thumbnail, extract_watermark, nsfw_check)
    watermark_result = add_watermark_via_service(input_video_path=local_video_path, output_video_path=output_video_path, task_id=task_id, watermark_size=resolution, extract_thumbnail=extract_thumbnail, extract_watermark=extract_watermark, nsfw_check=nsfw_check)
    watermark_results = {
        "status": 1,
        "code": "",
        "watermark": "",
        "thumbnail": "",
        "err_json": watermark_result.get("err_json")
    }
    print("watermark_result", watermark_result)
    if isinstance(watermark_result, dict) and watermark_result.get("status", 1) == 0:
        return watermark_result  # 直接返回错误信息

    if resolution != "0" or extract_watermark:
        # 3. 上传处理后的视频
        watermarked_video_path = output_video_path
        if watermarked_video_path and os.path.exists(watermarked_video_path):
            # 上传带水印的视频
            uploaded_watermark_key = sr_s3.upload_login_or_visitor(watermarked_video_path, s3_prefixes_path, serviceName=storage_service, bucketName=bucket_name)
            watermark_results["watermark"] = uploaded_watermark_key

    # 4. 如果有缩略图也上传
    if extract_thumbnail and os.path.exists(thumbnail_path):
        uploaded_thumbnail_key = sr_s3.upload_login_or_visitor(thumbnail_path, s3_prefixes_path, serviceName=storage_service, bucketName=bucket_name)
        watermark_results["thumbnail"] = uploaded_thumbnail_key
    return watermark_results


def check_content_review(data=None, resolution=None):
    # 1. 先处理字符串类型的data，转换为字典
    if isinstance(data, str):
        try:
            data = ast.literal_eval(data)  # 字符串转字典
        except SyntaxError:
            print("错误：data字符串格式不正确，无法转换为字典")
            return False  # 或根据需求返回其他默认值

    # 2. 处理data为None的情况，设置默认值
    if data is None:
        data = {'violence': 0.401, "sexual": 0.4}

    # 3. 确保data是字典类型（防御性检查）
    if not isinstance(data, dict):
        print("错误：data必须是字典或可转换为字典的字符串")
        return False

    if resolution is None:
        # 4. 定义各内容类别的阈值
        resolution = agent_config.RESOLUTION_CONTENT_REVIEW

    # 5. 遍历检查
    for key, value in data.items():
        # 额外检查：确保value是数值类型（避免字符串比较报错）
        if not isinstance(value, (int, float)):
            print(f"警告：{key}的值不是数值类型，跳过检查")
            continue
        if key in resolution:
            if value > resolution[key]:
                return True  # 有一个超过阈值就返回True
    return False

